<!--
  * 销售出库汇总(商品)
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="from" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="from.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="订单编号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="from.order_number" placeholder="订单编号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="业务员" class="smart-margin-bottom0" name="salesman_id">
            <Select name="Salesman" v-model:value="from.salesman_id" placeholder="业务员" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetData">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="4">
            <a-form-item label="出库仓库" name="warehouse_id" class="smart-margin-bottom0">
              <Select name="Warehouse" v-model:value="from.warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'	export:goods:statistics'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
        <a-button @click="detail()" type="primary" :disabled="selectedRowKeyList.length === 0" v-privilege="">
          <template #icon>
            <PlusOutlined />
          </template>
          查看商品明细
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ fixed: true, selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, column, record }">
          <template v-if="column.dataIndex === 'order_number'">
            <CopyText :text="text">
              {{ text }}
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'related_type'">
            {{ getDescByValue('RELATED_TYPE_ENUM', text) }}
          </template>
          <template v-if="column.dataIndex === 'name'">
            {{ record.store?.store_name ?? record.supplier?.name }}
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ record.warehouse?.name }}<span v-if="record.warehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.warehouse?.attribute_type) }})</span>
            </span>
          </template>
        </template>
        <template #summary>
          <a-table-summary-row fixed>
            <a-table-summary-cell :index="0">总计</a-table-summary-cell>
            <a-table-summary-cell />
            <a-table-summary-cell />
            <a-table-summary-cell />
            <a-table-summary-cell />
            <a-table-summary-cell
              ><a-typography-text type="danger">{{ sumData.total_goods_num }}</a-typography-text></a-table-summary-cell
            >
            <a-table-summary-cell
              ><a-typography-text type="danger">{{ Number(sumData.total_order_amount || 0) }}</a-typography-text></a-table-summary-cell
            >
            <a-table-summary-cell
              ><a-typography-text type="danger">{{ Number(sumData.total_service_fee || 0) }}</a-typography-text></a-table-summary-cell
            >
            <a-table-summary-cell :index="columns.length" />
          </a-table-summary-row>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="() => `共${total}条`" />
    </div>
    <goodsModal ref="detailRef" />
  </a-card>
</template>
<script setup lang="ts">
import goodsModal from './components/goods.vue'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import { outboundApi } from '@/api/business/report/goods-api'
import TableOperator from '@/components/support/table-operator/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useResize } from '@/hooks/web/use-resize-hook'
import Select from '@/components/business/select/index.vue'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import { useEnums } from '@/hooks/plugins/useEnums'
const { getDescByValue } = useEnums()
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '单据编号',
    dataIndex: 'order_number'
  },
  {
    title: '单据类型',
    dataIndex: 'related_type'
  },
  {
    title: '门店/供应商',
    dataIndex: 'name'
  },
  {
    title: '出库仓库',
    dataIndex: 'warehouse_name'
  },
  {
    title: '商品数量',
    dataIndex: 'total_goods_num'
  },

  {
    title: '订单金额',
    dataIndex: 'order_amount'
  },
  {
    title: '服务费',
    dataIndex: 'service_fee'
  },
  {
    title: '单据时间',
    dataIndex: 'create_time'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const from = ref({
  create_time: DEFAULT_TIME_RANGE.value,
  order_number: '',
  salesman_id: null,
  warehouse_id: null
})
const sumData = ref({
  total_goods_num: 0,
  total_order_amount: 0,
  total_service_fee: 0
})
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      create_time: from.value.create_time,
      order_number: from.value.order_number,
      warehouse_id: from.value.warehouse_id,
      salesman_id: from.value.salesman_id
    }
    const res = await outboundApi.outboundSummaryList(data)
    sumData.value.total_goods_num = `${res.data?.total_data?.total_goods_large_num || 0}整${res.data?.total_data?.total_goods_middle_num || 0}中${res.data?.total_data?.total_goods_small_num || 0}散`
    sumData.value.total_order_amount = res.data?.total_data?.total_order_amount
    sumData.value.total_service_fee = res.data?.total_data?.total_service_fee
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {},
  queryFormOp: {}
})
onMounted(() => {
  queryData()
})
// 搜索重置
const resetData = () => {
  from.value.create_time = DEFAULT_TIME_RANGE.value
  from.value.order_number = ''
  from.value.salesman_id = null
  from.value.warehouse_id = null
  queryData()
}

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: [WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value, WAREHOUSE_ATTRIBUTE_TYPE.TEMPORARY.value]
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['IN查询'] // 正库/处理库
    },
    fields: 'id,name'
  }
}

// ---------------------------- 批量 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([])

function onSelectChange(selectedRowKeys) {
  console.log(selectedRowKeys)
  selectedRowKeyList.value = selectedRowKeys
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = async () => {
  const data = {
    ids: selectedRowKeyList.value.join(',')
  }
  console.log(selectedRowKeyList.value.join(','))
  detailRef.value.showDrawer(data)
}

// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const data = {
    create_time: from.value.create_time,
    order_number: from.value.order_number,
    warehouse_id: from.value.warehouse_id,
    salesman_id: from.value.salesman_id
  }
  outboundApi.exportSummaryOrder(data)
}
</script>
